package dyu.Questionnaire;
import java.util.Calendar;
import java.util.Date;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service
{
	private PendingIntent pendingIntent;
	int timeInterval = 200; //seconds
	int notificationID = 12345;
	int intentBroadcastID = 168; 
	
	SharedPreferences prefs;
	String prefName = "PopupPref";
	int[] lastAnswerWeek;
    int[] currentAnswerStatus; 
    Date dateStarted;
    int numberOfGroups;
    //boolean isExpired = false;
	
	@Override
	public void onCreate() {
		Toast.makeText(this, "Creating service ...", Toast.LENGTH_LONG).show();
	}
	
	@Override
	public IBinder onBind(Intent intent) {
	 
		return null;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		
		this.SetUpAlarmInterval();
		
		Bundle extras = intent.getExtras();
		
		if(extras==null || extras.getString("timeCalled")==null) 
			this.PopUpToScreen();
		
		 
	}
	
	private void PopUpToScreen(){
		
		boolean isPopUp = this.CheckIfCanBePopup();
		
		if(isPopUp){
			Intent it = new Intent(getBaseContext(), MainActivity.class);
		    it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		    startActivity(it);
		    displayNotification();
		    stopSelf();
		}
		else{
			String ns = Context.NOTIFICATION_SERVICE;
			 NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
			 mNotificationManager.cancel(this.notificationID);
			 
//			 if(this.isExpired){
//				 this.StopAlarm();
//			 }
		}
	}
	 
	private void displayNotification(){
		 
		 String ns = Context.NOTIFICATION_SERVICE;
		 NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
		 
		 int icon = R.drawable.ic_launcher;
		 CharSequence tickerText = "Questionnaire Notification!";
		 long when = System.currentTimeMillis();

		 Notification notification = new Notification(icon, tickerText, when);
		 Intent notificationIntent = new Intent(this, MainActivity.class);
		 PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

		 long[] vibrate = {0, 2000,500,2000};
		 notification.setLatestEventInfo(this,"Questionnaire", "Please answer all the question!", contentIntent);
		 notification.vibrate = vibrate;
		 //notification.flags |= Notification.FLAG_AUTO_CANCEL;
		 notification.defaults |= Notification.DEFAULT_SOUND;
		 notification.defaults |= Notification.DEFAULT_LIGHTS;
		 mNotificationManager.notify(this.notificationID, notification);
		 
	}
	 
	private void SetUpAlarmInterval(){
    	 Intent myIntent = new Intent(this, MyService.class);
    	 
    	 pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
  	   	 AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

         Calendar calendar = Calendar.getInstance();
         calendar.setTimeInMillis(System.currentTimeMillis());
         calendar.add(Calendar.SECOND, timeInterval);
         alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
     }
	
	private void StopAlarm(){
		Intent intentstop = new Intent(this, MyService.class);
		PendingIntent senderstop = PendingIntent.getBroadcast(this, intentBroadcastID, intentstop, 0);
		AlarmManager alarmManagerstop = (AlarmManager) getSystemService(ALARM_SERVICE);
		alarmManagerstop.cancel(senderstop);
	}
    
	private int GetCurrentWeek(){
    	
		int currentWeek = 1;
		if(this.dateStarted == null) currentWeek = 1;
    	else{    		
    		Calendar calendar1 = Calendar.getInstance();
    		Calendar calendar2 = Calendar.getInstance();
    		
    		calendar1.setTime(Calendar.getInstance().getTime());//current date
    		calendar2.setTime(this.dateStarted);// beginning date
    		
    		//calculate the different days from these two days
    		long diffDays = (calendar1.getTimeInMillis() - calendar2.getTimeInMillis()) / (24 * 60 * 60 * 1000) + 1;
    		
    		if((diffDays) % 7 == 0 && diffDays != 0) currentWeek = (int) diffDays / 7;
    		else currentWeek = (int) diffDays/7 + 1;
    	}
    	
    	return currentWeek;
    }
	
	private void GetCurrentAnswerStatus(){
    	
    	int currentWeek = this.GetCurrentWeek();
    	
    	this.currentAnswerStatus = new int[this.numberOfGroups];
    	
    	for(int group=1; group<= this.numberOfGroups; group++){
    		
    		this.currentAnswerStatus[group-1] = 0;
    		
    		//check if this week requests the answer.
    		int popupID = this.getResources().getIdentifier("popupSchedule_Group" + group, "array", this.getPackageName());
    		
    		String[] weekList = getResources().getStringArray(popupID);
    		
			for(int i=0; i<weekList.length; i++){
				int temp = Integer.parseInt(weekList[i]);
				if(temp == currentWeek){
					this.currentAnswerStatus[group-1] = 1;
					break;
				}
				else if(temp > currentWeek) 
					break;
			}
			
			//check if this group of question be answered in this week?
			if(this.currentAnswerStatus[group-1] == 1){
				int lastAnswerWeekOfGroup = this.lastAnswerWeek[group-1];
				if(lastAnswerWeekOfGroup == currentWeek) 
					this.currentAnswerStatus[group-1] = 2;
			}
			
    	}
    }
	
	private void GetNumberOfGroup(){
    	int groupNumber = 1;
    	while(true){
        	
        	int ques = this.getResources().getIdentifier("Group" + groupNumber + "_Question", "array", this.getPackageName());
        	
        	if(ques==0) break;
        	
        	groupNumber++;
    	}
    	this.numberOfGroups = groupNumber - 1;
    }
    
    private void LoadOldData(){
    	this.lastAnswerWeek = new int[this.numberOfGroups];
    	
    	//------load all old variables data------------------
    	this.prefs = getSharedPreferences(this.prefName, MODE_PRIVATE);
    	//if(this.prefs == null) return;
    	
    	int day = this.prefs.getInt("day", 0);
    	int month = this.prefs.getInt("month", 0);
    	int year = this.prefs.getInt("year", 0);
    	
    	for(int i=0; i<this.numberOfGroups; i++){
    		this.lastAnswerWeek[i] = this.prefs.getInt("LastWeekAnswer"+i, 0);
    	}
    	
    	if(day ==0) {
    		this.dateStarted = null;
    		return;    	
    	}
    	this.dateStarted = new Date(year, month, day);
    	    	
    }

    public boolean CheckIfCanBePopup(){
     	
    	this.GetNumberOfGroup();
        this.LoadOldData();
        this.GetCurrentAnswerStatus();
    	
    	boolean isPopup = false;
     	if(this.dateStarted==null) isPopup = true;
     	else
	 		for(int i=0; i<this.numberOfGroups; i++){
				if(this.currentAnswerStatus[i]==1){
					isPopup = true;
					break;
				}
			}
     	
//     	if(isPopup = true && this.currentWeek>24)
//     		this.isExpired = true;
     	
 		return isPopup;
     }

}
				